package cn.coco.jf.fw.admin.sys.controller.index;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.NoUrlPara;

import cn.coco.jf.fw.core.db.SysMenuTbl;
import cn.coco.jf.fw.admin.controller.FwBaseController;
import cn.coco.jf.fw.admin.sys.dao.SysDao;

/**
 * 一句话简述
 * 详细描述
 * 
 * @version 1.0.0
 * @author Mark
 * @see 参照者
 * @since 1.0.1.1
 * @date 2017年6月19日
 */
@Before(NoUrlPara.class)
public class IndexController extends FwBaseController {
    
    public void index(){
        // 获取菜单数据
        List<SysMenuTbl> menuModelList = SysDao.querySysMenuTblListByRoleId(this.getRoleId());
        
        Map<Integer, JSONObject> topMenus = new HashMap<Integer, JSONObject>();

        for(SysMenuTbl entity:menuModelList){
            if(entity.getParentId() == 0){
                JSONObject topMenu = new JSONObject();
                topMenu.put("title", entity.getTitle());
                topMenu.put("icon", entity.getIcon());
                topMenu.put("spread", false);
                // 顶级菜单的场合
                topMenus.put(entity.getId(), topMenu);
            }
        }

        for(SysMenuTbl entity:menuModelList){
            if(entity.getParentId() != 0){
                JSONObject topMenu = topMenus.get(entity.getParentId());
                
                if(topMenu == null){
                    continue;
                }

                JSONObject childrenMenu = new JSONObject();
                childrenMenu.put("title", entity.getTitle());
                childrenMenu.put("icon", entity.getIcon());
                String menuUrl = entity.getMenuUrl();
                String[] menuUrls = menuUrl.split(",");
                childrenMenu.put("href", menuUrls[0]);
                
                if(topMenu.containsKey("children")){
                    JSONArray childrens = topMenu.getJSONArray("children");
                    
                    childrens.add(childrenMenu);
                }else{
                    JSONArray childrens = new JSONArray();
                    topMenu.put("children", childrens);
                    
                    childrens.add(childrenMenu);
                }
            }
        }

        List<JSONObject> menus = new ArrayList<JSONObject>();
        for(JSONObject json : topMenus.values()){
            menus.add(json);
        }
        
        this.setAttr("srcNavs", menus);
        
        this.render("index.html");
    }
}
